package scatter.order.rest.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import scatter.common.dict.PublicDictEnums;
import scatter.common.rest.exception.BusinessException;
import scatter.common.rest.validation.DictService;
import scatter.order.pojo.constant.OrderConstants;
import scatter.order.pojo.form.OrderCreateGoodsForm;
import scatter.order.pojo.param.CreateOrderParam;
import scatter.order.pojo.po.Order;
import scatter.order.pojo.po.OrderGoods;
import scatter.order.rest.service.IOrderGoodsService;
import scatter.order.rest.service.IOrderService;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author yangwei
 * @since 2021-06-27 16:06
 */
@Slf4j
public class DefaultCreateOrderFrameworkServiceImpl extends AbstractCreateOrderFrameworkServiceImpl<CreateOrderParam> {


	@Autowired
	protected IOrderService iOrderService;
	@Autowired
	protected DictService dictService;
	@Autowired
	protected IOrderGoodsService iOrderGoodsService;

	@Override
	protected boolean preCreateOrder(CreateOrderParam param) {
		if (OrderConstants.OrderPayChannelDictItem.wx_jsapi.itemValue().equals(param.getPayChannelDictValue())) {
			if(isStrEmpty(param.getMpAppCode())){
				throw new BusinessException("微信wx_jsapi支付时 mpAppCode 不能为空");
			}
		}

		if (param.getExpireAt() == null) {
			int invalidInMinute = 30;
			log.warn("没有设置订单失效时间，已默认设置为 {} 分钟后失效",invalidInMinute);
			param.setExpireAt(LocalDateTimeUtil.offset(LocalDateTime.now(),30, ChronoUnit.MINUTES));
		}

		return super.preCreateOrder(param);
	}

	@Override
	protected String doCreateOrder(CreateOrderParam param) {
		String orderNO = iOrderService.generateOrderNO(param.getCategoryDictValue());

		String categoryDictId = dictService.getIdByGroupCodeAndValue(OrderConstants.OrderCategoryGroupCode.order_category.groupCode(), param.getCategoryDictValue());

		String currencyDictValue = param.getCurrencyDictValue();
		if (isStrEmpty(param.getCurrencyDictValue())) {
			currencyDictValue = PublicDictEnums.CurrencyTypeDictItem.CNY.itemValue();
		}
		// 币种字典id
		String currencyDictId = dictService.getIdByGroupCodeAndValue(PublicDictEnums.CurrencyTypeGroupCode.currency_type.groupCode(), currencyDictValue);

		// 支付状态字典id，默认为待支付
		String statusDictId = dictService.getIdByGroupCodeAndValue(OrderConstants.OrderStatusGroupCode.order_status.groupCode(), OrderConstants.OrderStatusItem.wait_pay.itemValue());
		// 支付类型字典id
		String payTypeDictId = dictService.getIdByGroupCodeAndValue(OrderConstants.OrderPayTypeGroupCode.pay_type.groupCode(), param.getPayTypeDictValue());
		String payChannelDictId = dictService.getIdByGroupCodeAndValue(OrderConstants.OrderPayChannelDictItem.wx_jsapi.groupCode(), param.getPayChannelDictValue());
		Order order = new Order()
				.setOrderNo(orderNO)
				.setCategoryDictId(categoryDictId)
				.setClientIp(param.getClientIp())
				.setDescription(param.getDescription())
				.setTotalAmount(param.getTotalAmount())
				.setUserId(param.getUserId())
				.setCurrencyDictId(currencyDictId)
				.setTitle(param.getTitle())
				.setUserId(param.getUserId())
				.setChannelCode(param.getChannelCode())
				.setPayTypeDictId(payTypeDictId)
				.setStatusDictId(statusDictId)
				.setPayChannelDictId(payChannelDictId)
				// 设置订单在什么时间失效
				.setExpireAt(param.getExpireAt());

		boolean save = iOrderService.save(order);
		if (!save) {
			throw new RuntimeException("保存订单数据失败,因为save方法返回 false");
		}

		List<OrderGoods> goodsList = new ArrayList<>(param.getGoodsForms().size());
		OrderGoods goods = null;
		for (OrderCreateGoodsForm goodsForm : param.getGoodsForms()) {

			// 添加商品信息
			goods = new OrderGoods()
					.setOrderNo(orderNO)
					.setOrderId(order.getId())
					.setCategoryDictId(order.getCategoryDictId())
					.setGoodsId(goodsForm.getId())
					.setGoodsName(goodsForm.getName())
					.setGoodsDescription(goodsForm.getDescription())
					.setAmount(goodsForm.getAmount())
					.setCount(goodsForm.getCount())
					.setImageUrl(goodsForm.getImageUrl())
					.setAdditional(goodsForm.getAdditional())
					.setUserId(param.getUserId())
					// 添加商品和订单状态相同
			.setStatusDictId(statusDictId)
			;
			goodsList.add(goods);
		}
		boolean goodsSave = iOrderGoodsService.saveBatch(goodsList);

		if (!goodsSave) {
			throw new RuntimeException("保存商品信息数据失败,因为saveBatch方法返回 false");
		}
		// 其它三方支持
		thirdOtherOrder(param, order);

		return orderNO;
	}

	/**
	 * 其它第三方内部支付
	 * @param
	 * @param order
	 * @param param
	 */
	protected void thirdOtherOrder(CreateOrderParam param,Order order){}

	@Override
	public boolean support(String channel, String CategoryDictValue) {
		return false;
	}
}
